package com.shisfish.library.Controller;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;

import com.shisfish.library.Impl.BookLoanImpl;
import com.shisfish.library.Impl.BookMessageImpl;
import com.shisfish.library.Impl.UserSingleLendImpl;
import com.shisfish.library.Model.BookLoan;
import com.shisfish.library.Model.BookMessage;
import com.shisfish.library.Model.User;
import com.shisfish.library.Model.UserLevel;
import com.shisfish.library.Model.UserSingleLend;
import com.shisfish.library.Prere.BeforeLoan;
import com.shisfish.library.Prere.Login;
import com.shisfish.library.Utils.Global.GlobalVariable;
import com.shisfish.library.Utils.Global.toJsonUtils;
import com.shisfish.library.Utils.PageModel.Page;
import com.shisfish.library.Utils.PageModel.PageUtils;

@Path("bookLoan")
public class BookLoanController extends GlobalVariable {

	private BookLoanImpl bookLoanImpl = new BookLoanImpl();
	
	private BookMessageImpl bookMessageImpl = new BookMessageImpl();
	
	private UserSingleLendImpl userSingleLendImpl = new UserSingleLendImpl();
	
	@POST
	@Path("insertOne/{employee}")
	@Produces("application/json; charset=utf-8")
	public String insertOne(@PathParam("employee") String employee, @Context HttpServletRequest request, 
			@FormParam("isbn") String isbn, @FormParam("remarks") String remarks) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		BookLoan bookLoan = new BookLoan(isbn, employee, "", remarks, null, null);
		
		int flag = bookLoanImpl.insertOne(bookLoan);
		
		if (flag == 1) {
			globalMap.put(STATUS_CODE, SUCCESS);
		} else {
			globalMap.put(STATUS_CODE, INSERT_WR);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	/**
	 * @Author shisfish
	 * @Date 2016年1月3日 下午10:16:10
	 * @Descrition : 
	 * @param employee
	 * @param request
	 * @param isbn
	 * @param remarks
	 * @return
	 */
	@POST
	@Path("loanABook/{employee}/{isbn}")
	@Produces("application/json; charset=utf-8")
	public String loanABook(@PathParam("employee") String employee, @Context HttpServletRequest request, 
			@PathParam("isbn") String isbn, @FormParam("remarks") String remarks) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		if (Login.isLoginUser(employee, request)) {
			// 先判断书是否可预约
			List<BookMessage> bookMessages = bookMessageImpl.selectByKey(isbn);
			
			if (bookMessages.size() > 0) {
				BookMessage bookMessage = bookMessages.get(0);
				if (bookMessage.getIsBespeak() == 1 && bookMessage.getSurplus() == 0) {
					// 书可预约
					User user = BeforeLoan.isOverdueOrQuota(employee);
					
					// 人可预约
					if (user.getEmployee() != null) {
						
						if (user.getUserSingleLend().getLoan_number() > 0) {

							
							UserSingleLend userSingleLend = user.getUserSingleLend();
								
							Calendar cal = Calendar.getInstance();
							
							// 获得可借书时常
							int loan_days = user.getUserLevel().getLoan_borrow_days();
							
							cal.add(Calendar.DAY_OF_MONTH, loan_days);
							
							Date shouldCancelTime = cal.getTime();
							
							BookLoan bookLoan = new BookLoan(isbn, employee, user.getLoanid(), remarks, shouldCancelTime, null);
							
							int flag = bookLoanImpl.insertOne(bookLoan);
							
							if (flag == 1) {
								
								// 预约成功，个人借书信息更改
								userSingleLend.setLoaned_number(userSingleLend.getLoaned_number() + 1);
								
								int flag_1 = userSingleLendImpl.updateOne(userSingleLend);
								
								if (flag_1 == 1) {
									globalMap.put(STATUS_CODE, SUCCESS);
								}
								else {
									globalMap.put(STATUS_CODE, UPDATE_WR);
								}
								
								// 书类信息更改
								bookMessage.setNumber(bookMessage.getNumber() + 1);
								
								int flag_2 = bookMessageImpl.updateOne(bookMessage);
								
								if (flag_2 == 1) {
									globalMap.put(STATUS_CODE, SUCCESS);
								}
								else {
									globalMap.put(STATUS_CODE, UPDATE_WR);
								}
							}
							else {
								globalMap.put(STATUS_CODE, INSERT_WR);
							}
							
						
						} else {

							// 新增用户借书信息
							// 先查询用户的等级
							UserLevel userLevel = user.getUserLevel();
							
							UserSingleLend userSingleLend = new UserSingleLend(employee, 0, 0, userLevel.getBorrow_numbers(), userLevel.getLoan_numbers(), user.getLoanid());
							
							int flag = userSingleLendImpl.insertOne(userSingleLend);
							
							if (flag == 1) {
							
								// 未预约过书，可预约
								
								Calendar cal = Calendar.getInstance();
								
								// 获得可借书时常
								int loan_days = user.getUserLevel().getLoan_borrow_days();
								
								cal.add(Calendar.DAY_OF_MONTH, loan_days);
								
								Date shouldCancelTime = cal.getTime();
								
								BookLoan bookLoan = new BookLoan(isbn, employee, user.getLoanid(), remarks, shouldCancelTime, null);
								
								int flag_2 = bookLoanImpl.insertOne(bookLoan);
								
								if (flag_2 == 1) {
									
									// 预约成功，个人借书信息更改
									userSingleLend.setLoaned_number(userSingleLend.getLoaned_number() + 1);
									
									int flag_1 = userSingleLendImpl.updateOne(userSingleLend);
									
									if (flag_1 == 1) {
										globalMap.put(STATUS_CODE, SUCCESS);
									}
									else {
										globalMap.put(STATUS_CODE, UPDATE_WR);
									}
									
									// 书类信息更改
									bookMessage.setNumber(bookMessage.getNumber() + 1);
									
									int flag_3 = bookMessageImpl.updateOne(bookMessage);
									
									if (flag_3 == 1) {
										globalMap.put(STATUS_CODE, SUCCESS);
									}
									else {
										globalMap.put(STATUS_CODE, UPDATE_WR);
									}
								}
								
							}
							else {
								globalMap.put(STATUS_CODE, INSERT_WR);
							}
						
						}
						
					} else {
						// 人不可预约
						globalMap.put(STATUS_CODE, OVERDUE_QUOTA);
					}
					
				} else {
					// 书不可预约
					globalMap.put(STATUS_CODE, OVERDUE_QUOTA);
				}
			} else if (bookMessages.size() == 0) {
				globalMap.put(STATUS_CODE, SELECT_EMPTY);
			} else {
				globalMap.put(STATUS_CODE, SELECT_WR);
			}
		} else {
			globalMap.put(STATUS_CODE, NOT_LOGGED_IN);
		}
		return toJsonUtils.map2Json(globalMap);
	}
	
	/**
	 * @Author shisfish
	 * @Date 2016年1月4日 下午3:16:13
	 * @Descrition : 取消预约
	 * @param employee
	 * @param request
	 * @param isbn
	 * @return
	 */
	@POST
	@Path("cancelALoan/{employee}/{isbn}")
	@Produces("application/json; charset=utf-8")
	public String cancelALoan(@PathParam("employee") String employee, @Context HttpServletRequest request, 
			@PathParam("isbn") String isbn) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		if (Login.isLoginUser(employee, request)) {
			List<BookLoan> bookLoans = bookLoanImpl.selectByISBNUser(employee, isbn);
			
			if (bookLoans.size() > 0) {
				
				BookLoan bookLoan = bookLoans.get(0);
				bookLoan.setActualCancelTime(new Date());
				int flag = bookLoanImpl.updateOne(bookLoan);
				
				if (flag == 1) {
					// 更改个人纪录信息
					List<UserSingleLend> userSingleLends = userSingleLendImpl.selectByKey(employee);
					if (userSingleLends.size() > 0) {
						UserSingleLend userSingleLend = userSingleLends.get(0);
						userSingleLend.setLoaned_number(userSingleLend.getLoaned_number() - 1);
						int flag_1 = userSingleLendImpl.updateOne(userSingleLend);
						
						if (flag_1 == 1) {
							globalMap.put(STATUS_CODE, SUCCESS);
						} else {
							globalMap.put(STATUS_CODE, UPDATE_WR);
						}
					} else if (userSingleLends.size() == 0) {
						globalMap.put(STATUS_CODE, SELECT_EMPTY);
					} else {
						globalMap.put(STATUS_CODE, SELECT_WR);
					}
					
					// 书类信息修改
					List<BookMessage> bookMessages = bookMessageImpl.selectByKey(isbn);
					if (bookMessages.size() > 0) {
						BookMessage bookMessage = bookMessages.get(0);
						bookMessage.setNumber(bookMessage.getNumber() - 1);
						int flag_1 = bookMessageImpl.updateOne(bookMessage);
						
						if (flag_1 == 1) {
							globalMap.put(STATUS_CODE, SUCCESS);
						} else {
							globalMap.put(STATUS_CODE, UPDATE_WR);
						}
					} else if (bookMessages.size() == 0) {
						globalMap.put(STATUS_CODE, SELECT_EMPTY);
					} else {
						globalMap.put(STATUS_CODE, SELECT_WR);
					}
					
				} else {
					globalMap.put(STATUS_CODE, UPDATE_WR);
				}
				
			} else if (bookLoans.size() == 0) {
				globalMap.put(STATUS_CODE, SELECT_EMPTY);
			} else {
				globalMap.put(STATUS_CODE, SELECT_WR);
			}
			
		} else {
			globalMap.put(STATUS_CODE, NOT_LOGGED_IN);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	/**
	 * @Author shisfish
	 * @Date 2016年1月7日 下午3:12:40
	 * @Descrition : 查询用户预约书信息（分页）
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	@GET
	@Path("loanMessage/{currentPage}/{pageSize}")
	@Produces("application/json; charset=utf-8")
	public String loanMessage(@PathParam("currentPage") int currentPage, @PathParam("pageSize") int pageSize) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		int count = bookLoanImpl.countAll();
		
		if (count > 0) {
			Page page = PageUtils.createPage(count, currentPage, pageSize);
			
			List<Map<String, Object>> test = bookLoanImpl.selectAllMessage(page.getBeginIndex(), pageSize);
			
			if (test.size() > 0) {
				globalMap.put("list", test);
				globalMap.put(STATUS_CODE, SUCCESS);
			} else if (test.size() == 0) {
				globalMap.put(STATUS_CODE, SELECT_EMPTY);
			} else {
				globalMap.put(STATUS_CODE, SELECT_WR);
			}
		} else if (count == 0) {
			globalMap.put(STATUS_CODE, SELECT_EMPTY);
		} else {
			globalMap.put(STATUS_CODE, SELECT_WR);
		}
		return toJsonUtils.map2Json(globalMap);
	}
	
	/**
	 * @Author shisfish
	 * @Date 2016年1月7日 下午4:30:55
	 * @Descrition : 查询某天预约书记录
	 * @param idadmin
	 * @param choDate
	 * @param request
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	@POST
	@Path("selectByDate/{idadmin}/{currentPage}/{pageSize}")
	@Produces("application/json; charset=utf-8")
	public String selectByDate(@PathParam("idadmin") String idadmin, @FormParam("choDate") String choDate, 
			@Context HttpServletRequest request, 
			@PathParam("currentPage") int currentPage, @PathParam("pageSize") int pageSize) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		if (Login.isLoginAdmin(idadmin, request)) {
			
			int count = bookLoanImpl.countByDate(choDate);
			
			if (count > 0) {
				
				Page page = PageUtils.createPage(count, currentPage, pageSize);
				List<Map<String, Object>> bookLoans = bookLoanImpl.selectByDate(choDate, page.getBeginIndex(), pageSize);
				
				if (bookLoans.size() > 0) {
					globalMap.put("list", bookLoans);
					globalMap.put("page", page);
					globalMap.put(STATUS_CODE, SUCCESS);
				} else if (bookLoans.size() == 0) {
					globalMap.put(STATUS_CODE, SELECT_EMPTY);
				} else {
					globalMap.put(STATUS_CODE, SELECT_WR);
				}
			} else if (count == 0) {
				globalMap.put(STATUS_CODE, SELECT_EMPTY);
			} else {
				globalMap.put(STATUS_CODE, SELECT_WR);
			}
		} else {
			globalMap.put(STATUS_CODE, NOT_LOGGED_IN);
		}
		
		return toJsonUtils.map2Json(globalMap);
		
	}
	
	/**
	 * @Author shisfish
	 * @Date 2016年1月7日 下午4:31:19
	 * @Descrition : 查询某天预约书记录（按预约者排序）
	 * @param idadmin
	 * @param choDate
	 * @param request
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	@POST
	@Path("loanLogByDate/{idadmin}/{currentPage}/{pageSize}")
	@Produces("application/json; charset=utf-8")
	public String loanLogByDate(@PathParam("idadmin") String idadmin, @FormParam("choDate") String choDate, 
			@Context HttpServletRequest request, 
			@PathParam("currentPage") int currentPage, @PathParam("pageSize") int pageSize) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		if (Login.isLoginAdmin(idadmin, request)) {
			
			int count = bookLoanImpl.countLoanLogByDate(choDate);
			
			if (count > 0) {
				Page page = PageUtils.createPage(count, currentPage, pageSize);
				List<Map<String, Object>> bookLoans = bookLoanImpl.loanLogByDate(choDate, page.getBeginIndex(), pageSize);
				
				if (bookLoans.size() > 0) {
					globalMap.put("list", bookLoans);
					globalMap.put("page", page);
					globalMap.put(STATUS_CODE, SUCCESS);
				} else if (bookLoans.size() == 0) {
					globalMap.put(STATUS_CODE, SELECT_EMPTY);
				} else {
					globalMap.put(STATUS_CODE, SELECT_WR);
				}
			} else if (count == 0) {
				globalMap.put(STATUS_CODE, SELECT_EMPTY);
			} else {
				globalMap.put(STATUS_CODE, SELECT_WR);
			}
			
		} else {
			globalMap.put(STATUS_CODE, NOT_LOGGED_IN);
		}
		
		return toJsonUtils.map2Json(globalMap);
		
	}

	/**
	 * @Author shisfish
	 * @Date 2016年1月7日 下午4:31:42
	 * @Descrition : 通过预约书者id查询某天预约书记录
	 * @param idadmin
	 * @param userId
	 * @param choDate
	 * @param request
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	@POST
	@Path("loanLogByDateLoaner/{idadmin}/{currentPage}/{pageSize}")
	@Produces("application/json; charset=utf-8")
	public String loanLogByDateLoaner(@PathParam("idadmin") String idadmin, @FormParam("userId") String userId, 
			@FormParam("choDate") String choDate, @Context HttpServletRequest request, 
			@PathParam("currentPage") int currentPage, @PathParam("pageSize") int pageSize) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		if (Login.isLoginAdmin(idadmin, request)) {
			
			int count = bookLoanImpl.countLoanLogByDateLoaner(userId, choDate);
			
			if (count > 0) {
				Page page = PageUtils.createPage(count, currentPage, pageSize);
				List<Map<String, Object>> bookLoans = bookLoanImpl.loanLogByDateLoaner(userId, choDate, page.getBeginIndex(), pageSize);
				if (bookLoans.size() > 0) {
					globalMap.put("list", bookLoans);
					globalMap.put("page", page);
					globalMap.put(STATUS_CODE, SUCCESS);
				} else if (bookLoans.size() == 0) {
					globalMap.put(STATUS_CODE, SELECT_EMPTY);
				} else {
					globalMap.put(STATUS_CODE, SELECT_WR);
				}
			} else if (count == 0) {
				globalMap.put(STATUS_CODE, SELECT_EMPTY);
			} else {
				globalMap.put(STATUS_CODE, SELECT_WR);
			}
			
		} else {
			globalMap.put(STATUS_CODE, NOT_LOGGED_IN);
		}
		
		return toJsonUtils.map2Json(globalMap);
		
	}
	
	/**
	 * @Author shisfish
	 * @Date 2016年1月14日 下午5:09:39
	 * @Descrition : 但本书的预约记录（分页）
	 * @param isbn
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	@GET
	@Path("bookLoanLog/{isbn}/{currentPage}/{pageSize}")
	@Produces("application/json; charset=utf-8")
	public String bookLoanLog(@PathParam("isbn") String isbn, @PathParam("currentPage") int currentPage, @PathParam("pageSize") int pageSize) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		int count = bookLoanImpl.bookLogCount(isbn);
		
		if (count > 0) {
			Page page = PageUtils.createPage(count, currentPage, pageSize);
			List<Map<String, Object>> log = bookLoanImpl.bookLogPage(isbn, page.getBeginIndex(), pageSize);
			
			if (log.size() > 0) {
				globalMap.put(STATUS_CODE, SUCCESS);
				globalMap.put("page", page);
				globalMap.put("list", log);
			} else if (log.size() == 0) {
				globalMap.put(STATUS_CODE, SELECT_EMPTY);
			} else {
				globalMap.put(STATUS_CODE, SELECT_WR);
			}
		} else if (count == 0) {
			globalMap.put(STATUS_CODE, SELECT_EMPTY);
		} else {
			globalMap.put(STATUS_CODE, SELECT_WR);
		}
		return toJsonUtils.map2Json(globalMap);
	}

}
